#include "app_bluetooth.h"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include "app_message.h"
#include <assert.h>
#include "log/log.h"

// 读缓存，负责拼接数据帧
static char read_buf[1024];
// 缓存中现有数据的长度
static int read_len = 0;
// 默认数据帧头
static char fixed_header[] = {0xF1, 0xDD};

static int app_bluetooth_waitACK(Device *device)
{
    char buf[32];
    memset(buf, 0, 32);
    int len = read(device->fd, buf, 32);
    log_trace("read %d bytes: %s", len, buf);
    if (memcmp(buf, "OK\r\n", 4) == 0)
    {
        return 0;
    }
    return -1;
}

int app_bluetooth_status(Device *device)
{
    write(device->fd, "AT\r\n", 4);
    return app_bluetooth_waitACK(device);
}

int app_bluetooth_reset(Device *device)
{
    write(device->fd, "AT+RESET\r\n", 10);
    return app_bluetooth_waitACK(device);
}

int app_bluetooth_rename(Device *device, char *name)
{
    write(device->fd, "AT+NAME", 7);
    write(device->fd, name, strlen(name));
    write(device->fd, "\r\n", 2);
    return app_bluetooth_waitACK(device);
}

int app_bluetooth_setBaudRate(Device *device, BT_BAUD baud)
{
    switch (baud)
    {
    case BT_BAUD_9600:
        write(device->fd, "AT+BAUD4\r\n", 10);
        break;
    case BT_BAUD_115200:
        write(device->fd, "AT+BAUD8\r\n", 10);
        break;
    default:
        break;
    }
    return app_bluetooth_waitACK(device);
}

int app_bluetooth_setMAddr(Device *device, char *maddr)
{
    write(device->fd, "AT+MADDR", 8);
    write(device->fd, maddr, 4);
    write(device->fd, "\r\n", 2);
    return app_bluetooth_waitACK(device);
}

int app_bluetooth_setNetID(Device *device, char *netid)
{
    write(device->fd, "AT+NETID", 8);
    write(device->fd, netid, 4);
    write(device->fd, "\r\n", 2);
    return app_bluetooth_waitACK(device);
}

static void app_bluetooth_moveData(int n)
{
    if (n < read_len)
    {
        memmove(read_buf, read_buf + n, read_len - n);
        read_len -= n;
    }
    else
    {
        read_len = 0;
    }
}

int app_bluetooth_postRead(Device *device, void *dat, int len)
{
    unsigned char *data = dat;
    // 进来的数据是蓝牙格式，需要返回msg格式。
    // 首先将数据拷贝到读缓存
    memcpy(read_buf + read_len, data, len);
    read_len += len;

    // 首先要保证缓存中至少有4个字节
    if (read_len < 4)
    {
        return 0;
    }
    // 分析帧头
    int i = 0;
    for (i = 0; i < read_len - 3; i++)
    {
        if (memcmp(read_buf + i, "OK\r\n", 4) == 0)
        {
            // 收到ACK
            // 处理ACK
            device->last_write_time = 0;
            // 略过消息
            app_bluetooth_moveData(i + 4);
            log_debug("ACK received");
            return 0;
        }
        else if (memcmp(read_buf + i, fixed_header, 2) == 0)
        {
            if (i > 0)
            {
                app_bluetooth_moveData(i);
            }
            if (read_len < read_buf[2] + 3)
            {
                // 数据帧不完整，暂时不处理
                return 0;
            }
            // 到这里，数据帧是完整的，向data缓冲区中拷贝
            data[0] = CONN_BT;
            data[1] = 2;
            data[2] = read_buf[2] - 4;
            // 拷贝ID
            memcpy(data + 3, read_buf + 3, data[1]);
            // 拷贝数据
            memcpy(data + 5, read_buf + 7, data[2]);

            // 略过这条消息
            app_bluetooth_moveData(read_buf[2] + 3);
            return data[2] + 5;
        }
    }
    app_bluetooth_moveData(i);
    return 0;
}

int app_bluetooth_preWrite(Device *device, void *dat, int len)
{
    assert(device);
    assert(len > 3);
    unsigned char *data = dat;
    len = data[2] + 12;
    char buf[32];
    memcpy(buf, "AT+MESH", 8);
    memcpy(buf + 8, data + 3, 2);
    memcpy(buf + 10, data + 5, data[2]);
    memcpy(buf + 10 + data[2], "\r\n", 2);
    memcpy(data, buf, len);
    for (size_t i = 0; i < len; i++)
    {
        printf("%02x ", data[i]);
    }
    printf("\n");
    
    return len;
}
